<template>
	<a-modal title="授权管理" :visible="visible" @ok="handleOk">
		<a-tree
			v-model:expandedKeys="expandedKeys"
			v-model:selectedKeys="selectedKeys"
			v-model:checkedKeys="checkedKeys"
			checkable
			style="height: 460px; overflow: auto"
			:replaceFields="replaceFields"
			checkStrictly="true"
			:tree-data="treeData"
      defaultExpandAll="true"
		>
			<template #title="{ name, key }">
		  
				<span v-if="key === '0-0-1-0'" style="color: #1890ff"
					>{{name}}</span
				>
				<template v-else>{{name}}</template>
			</template>
		</a-tree>
	</a-modal>
</template>

<script>
// 表单字段
import tree from 'vue-giant-tree'
import {
	defineComponent,
	reactive,
	ref,
	onMounted,
	nextTick,
	computed,
	getCurrentInstance,
	watch
} from 'vue'
import { useStore, mapGetters } from 'vuex'
import { AllgrantAuth } from '/@/api/app.js'

function arrToTree(arr, pid = null) {
	const res = []
	arr.forEach((item) => {
		if (item.pid === pid) {
			// 这样每次都需要遍历整个数组，因此时间复杂度为 n*n
			// const children = arrToTree(arr, item.id)

			// 往下递归时，每次数组的大小都在减小，每次都筛选掉父代元素，最终的时间复杂度为 n*logn
			const children = arrToTree(
				arr.filter((v) => v.pid !== pid),
				item.id
			)
			if (children.length) {
				res.push({ ...item, children })
			} else {
				res.push({ ...item })
			}
		}
	})
	return res
}
export default defineComponent({
	props: {
		visible: {
			type: Boolean,
			required: true
		},
		loading: {
			type: Boolean,
			default: () => false
		},
		model: {
			type: Object,
			default: () => null
		}
	},
	emits: {
		handleok: null
	},

	setup(props, context) {
		const expandedKeys = ref([])
		const selectedKeys = ref([])
		const checkedKeys = ref([])
		const treeData = ref([])
		const replaceFields = ref({
			children: 'children',
			title: 'name',
			key: 'id'
		})
		const handleOk = () => {
			context.emit('handleok', checkedKeys)
		}
		watch(expandedKeys, () => {
			console.log('expandedKeys', expandedKeys)
		})
		watch(selectedKeys, () => {
			console.log('selectedKeys', selectedKeys)
		})
		watch(checkedKeys, () => {
			console.log('checkedKeys', checkedKeys)
		})
		const GetgrantAuth = (id) => {
			AllgrantAuth(id)
				.then((res) => {
					const {
						result: { list, auth }
					} = res
					var authdata = (auth && auth.length && auth.split(',')) || []

					// treeData.value =(toTreeData(list))
					treeData.value = arrToTree(list, 0)
					console.log(arrToTree(list, 0))
					if (authdata.length > 0) {
						expandedKeys.value = authdata.map(Number)
						selectedKeys.value = authdata.map(Number)

						checkedKeys.value = authdata.map(Number)
					}
				})
				.catch(() => {})
		}
		onMounted(() => {
			const { id } = props.model
			GetgrantAuth(id)
		})
		return {
			replaceFields,
			treeData,
			expandedKeys,
			selectedKeys,
			checkedKeys,
			GetgrantAuth,
			handleOk
		}
	}
})
</script>

<style scoped>
</style>
